package top.hhydra.mimall.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;
import top.hhydra.mimall.entity.User;
import top.hhydra.mimall.enums.ResponseEnum;
import top.hhydra.mimall.mapper.UserMapper;
import top.hhydra.mimall.service.IUserService;
import top.hhydra.mimall.vo.ResponseVo;

import java.nio.charset.StandardCharsets;

import static top.hhydra.mimall.enums.RoleEnum.CUSTOMER;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author SaiyaEmon
 * @since 2020-02-08
 */
@Service
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    /**
     * 注册
     *
     * @param user
     * @return
     */
    @Override
    public ResponseVo<User> register(User user) {
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("username", user.getUsername());
        Integer usernameCount = baseMapper.selectCount(userQueryWrapper);
        if (usernameCount > 0) {
            return ResponseVo.error(ResponseEnum.USERNAME_EXISTS);
        }

        userQueryWrapper.clear();
        userQueryWrapper.eq("email", user.getEmail());
        Integer emailCount = baseMapper.selectCount(userQueryWrapper);
        if (emailCount > 0) {
            return ResponseVo.error(ResponseEnum.EMAIL_EXISTS);
        }

        user.setRole(CUSTOMER.getCode());
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8)));

        int insertUserCount = baseMapper.insert(user);
        if (insertUserCount == 0) {
            return ResponseVo.error(ResponseEnum.ERROR);
        }
        return ResponseVo.success();
    }

    /**
     * 登录
     *
     * @param user
     * @return
     */
    @Override
    public ResponseVo<User> login(User user) {
        String password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes(StandardCharsets.UTF_8));
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("password", password);
        userQueryWrapper.eq("username", user.getUsername());
        User selectUser = baseMapper.selectOne(userQueryWrapper);
        if (selectUser == null) {
            return ResponseVo.error(ResponseEnum.USERNAME_OR_PASSWORD_ERROR);
        }

        selectUser.setPassword("");

        return ResponseVo.success(selectUser);
    }
}
